package jjn.round1;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jiang Jining
 * @since 2022-07-22 23:59
 */
public class LeetCode46_Permutations {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        backtrack(nums, 0, new ArrayList<>(), result);
        return result;
    }
    
    private void backtrack(int[] nums, int stage, List<Integer> path, List<List<Integer>> result) {
        if (stage == nums.length) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int ithNum : nums) {
            // path中已经用过此元素则忽略
            if (path.contains(ithNum)) {
                continue;
            }
            path.add(ithNum);
            backtrack(nums, stage + 1, path, result);
            // 撤销所选,换下一个数继续
            path.remove(path.size() - 1);
        }
    }
}
